package net.ck.hzq;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import java.net.URL;
import java.util.HashMap;

import Utils.ResourcesManager;
import base.BaseActivity;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import dao.HomeNewsBean;
import util.LogUtils;
import util.StringUtils;
import util.ToastUtils;

public class NewsWebViewActivity extends BaseActivity implements View.OnClickListener {

    private WebView webview;
    private ImageView back;
    private ImageView share;
    HomeNewsBean bean;

    public static void start(Context context, HomeNewsBean url) {
        Intent intent = new Intent(context, NewsWebViewActivity.class);
        intent.putExtra("HomeNewsBean", url);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_news_webview;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webview = findViewById(R.id.webview);
        back = findViewById(R.id.iv_back);
        share = findViewById(R.id.iv_share);
        back.setOnClickListener(this);
        share.setOnClickListener(this);
        bean = (HomeNewsBean) getIntent().getSerializableExtra("HomeNewsBean");
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
//        webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");
        webview.loadUrl(bean.getUrl());
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:")) {
                    view.loadUrl(url);
                    return true;
                }
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });

        findViewById(R.id.iv_back).setOnClickListener(v -> finish());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_share:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            onOneKeyShare();
                        } catch (Exception e) {
                            ToastUtils.shortToast(e.getMessage() + "");
                            e.printStackTrace();

                        }
                    }
                }).start();
                break;
        }
    }

    /**
     * 一键分享
     */
    private void onOneKeyShare() {
        //TODO
        cn.sharesdk.onekeyshare.OnekeyShare oks = new cn.sharesdk.onekeyshare.OnekeyShare();
        oks.setAddress("http://www.tobuy.net/");
        ResourcesManager manager = ResourcesManager.getInstace(NewsWebViewActivity.this);
        oks.setTitle(bean.getBt());//标题
        oks.setText("好钻钱");//内容
        oks.setUrl(bean.getUrl());//链接
        oks.setTitleUrl(bean.getUrl());
        Bitmap thumbBmp = null;
        if (StringUtils.isEmpty(bean.getNewImag())) {
            thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo_new);
        } else {
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(new URL(bean.getNewImag()).openStream());
                thumbBmp = Bitmap.createScaledBitmap(bitmap, 120, 150, true);
            } catch (Exception e) {
                LogUtils.d("-----------");
            }
        }
        oks.setImageData(thumbBmp);
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " completed at " + msg;
                Message message = new Message();
                message.obj = text;
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + "caught error at " + msg;
                Message message = new Message();
                message.obj = text;
            }

            @Override
            public void onCancel(Platform platform, int i) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " canceled at " + msg;
                Message message = new Message();
                message.obj = text;
            }
        });
        oks.show(NewsWebViewActivity.this);
    }


    /**
     * 设置缩略图
     *
     * @param bitMap
     * @param needRecycle
     * @return
     */
    public static Bitmap createBitmapThumbnail(Bitmap bitMap, boolean needRecycle) {
        int width = bitMap.getWidth();
        int height = bitMap.getHeight();
        // 设置想要的大小
        int newWidth = 80;
        int newHeight = 80;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,
                matrix, true);
        if (needRecycle) bitMap.recycle();
        return newBitMap;
    }
}
